using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Asteriod : MonoBehaviour
{
    private Rigidbody2D _rigidbody2D;
    private SpriteRenderer _spriteRenderer;
    [SerializeField] private Sprite[] sprites;
    public float _size = 1.0f;
    public float _mixSize = 0.5f;
    public float _maxSize = 2.0f;

    [SerializeField]
    private float speed = 50.0f;

    private void Awake()
    {
        _spriteRenderer = GetComponent<SpriteRenderer>();
        _rigidbody2D = GetComponent<Rigidbody2D>();
    }

    private void Start()
    {
        _spriteRenderer.sprite = sprites[Random.Range(0, sprites.Length)];

        transform.eulerAngles = new Vector3(0f, 0f, Random.value * 360f);

        transform.localScale = Vector3.one * _size;

        _rigidbody2D.mass = _size;
    }

    public void SetTrajectory(Vector3 direction)
    {
        _rigidbody2D.AddForce(direction * speed);
        GameObject.Destroy(gameObject, 30f);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Bullet"))
        {
            GameObject.FindWithTag("GameManager").GetComponent<GameManager>().AsteroidDestroy(this);
            //FindObjectOfType<GameManager>().AsteroidDestroy(this);
            if ((_size / 2) >= 0.6f)
            {
                CreateSplit();
                CreateSplit();
            }
            Destroy(gameObject);
        }
    }

    private void CreateSplit()
    {
        Vector2 position = transform.position;
        position += Random.insideUnitCircle * 0.5f;

        Asteriod half = Instantiate(this, position, transform.rotation);
        half._size = _size / 2;
        half.SetTrajectory(Random.insideUnitCircle.normalized * speed);
    }
}